package com.mbcn.dao.impl;

import java.util.ArrayList;
import java.util.List;






import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;






import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.mbcn.dao.ItemDAO;
import com.mbcn.model.Item;
import com.mbcn.model.Member;
import com.mbcn.system.commonUtil.Util;
import com.mbcn.system.hibernateUtil.HibernateUtil;
 
public class ItemDAOImpl implements ItemDAO{
	@SessionTarget
	Session session;
	     
	@TransactionTarget
	Transaction transaction;
	HttpServletRequest request = ServletActionContext.getRequest();

	public void addItem(Item item) {
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			session.save(item);
			transaction.commit();
			session.close();
	        	String realPath = request.getSession().getServletContext()
				.getRealPath("/");
	        	Util.copyfile(realPath +"imagesUserUploaded_tmp/"+ item.getItemImage(), realPath+ "imagesUserUploaded/"+ item.getItemImage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}



	@SuppressWarnings("unchecked")
	public List<Item> listItemByCategory(int category) {
		List<Item> items = new ArrayList<Item>();
		try {
			//HibernateUtil.getSessionFactory().openSession();
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
	        
	        
	        String hql = "FROM Item I WHERE I.itemCategory = :Category order by I.itemDatePost desc";
	        Query query = session.createQuery(hql);
	        query.setParameter("Category",category);
	        items = query.list();
	        
	        
			//items = session.createQuery("from MbcnItems where MbcnItems=:Category").setParameter("Category", category).list();
			transaction.commit();
			session.close();
			
		} catch (Exception e) {
			 e.printStackTrace();
	        
		}
		
		return items;
	}



	



//	public List<Item> listItemByCategory(int category) {
//		// TODO Auto-generated method stub
//		return null;
//	}

	
	
	
}